package com.qingrongby.shop.core;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;

public class AutoUrlPrefix extends RequestMappingHandlerMapping {

    @Value("${shop-base-api}")
    protected String basePackage;

    @Override
    protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
        RequestMappingInfo requestMappingInfo = super.getMappingForMethod(method, handlerType);
        if (requestMappingInfo != null) {
            String packageName = handlerType.getPackage().getName();
            String baseUrl = getPackage(packageName);

            return RequestMappingInfo.paths(baseUrl).build().combine(requestMappingInfo);
        }


        return requestMappingInfo;
    }

    /**
     * 处理自动填充基础包
     *
     * @param packageName
     * @return
     */
    private String getPackage(String packageName) {
        String newPackage = packageName.replace(basePackage, "");
        return newPackage.replace(".", "/");
    }

}
